<template>
  <div class="flexContent">
    <div class="searchBox">
      <el-form ref="formRef" class="demo-form-inline" @submit.native.prevent label-position="left" label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="商品">
                  <el-input v-model="name" style="width: 95%" placeholder="请输入..." clearable
                    @keyup.enter.native="searchFn" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="btnBox">
            <el-button @click.stop="searchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button @click.stop="resetFn" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <div class="add">
      <el-button class="addBtn" @click="addFn">新增</el-button>
    </div>
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;">
        <vxe-table :column-config="{ resizable: true }" class="tablebox" border ref="xTable1"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="100%"
          align="center">
          <vxe-column type="seq" title="序号" width="80"></vxe-column>
          <vxe-column field="name" title="商品名称" />
          <vxe-column field="unit" title="包装单位" />
          <vxe-column field="producerArea" title="产地" />
          <vxe-column field="imgUrl" title="图片">
            <template v-slot="{ row }">
              <div class="img" style="padding-top: 10px">
                <img style="width: 50px" :src="row.imgUrl" alt="" />
              </div>
            </template>
          </vxe-column>
          <vxe-column title="操作" fixed="right" width="150">
            <template v-slot="{ row }">
              <el-button slot="reference" style="color: rgb(0, 132, 255); margin-right: 10px" type="text" size="big"
                @click.stop="edit(row)">修改</el-button>
              <el-button type="text" size="big" style="margin-right: 10px; color: red"
                @click="$delFn('扶农商品', del, row)">删除</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,->, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <AddDialog :close-on-click-modal="false" :is-show-btn="isShowBtn" :show-dialog.sync="showDialog" :width="width"
      :title="title" @btnOk="btnOk" @close="close">
      <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="120px">
        <el-form-item label="商品名称" style="width: 100%" prop="name">
          <el-input v-model="addForm.name" />
        </el-form-item>
        <el-form-item label="包装单位" style="width: 100%" prop="name">
          <el-input v-model="addForm.unit" />
        </el-form-item>
        <el-form-item label="产地" style="width: 100%" prop="producerArea">
          <el-input v-model="addForm.producerArea" />
        </el-form-item>
        <el-form-item :label="'消耗' + $tokenName + '数'" style="width: 100%" prop="consumeNum">
          <el-input v-model="addForm.consumeNum" />
        </el-form-item>
        <el-form-item label="最大兑换数量" style="width: 100%" prop="maxExchange">
          <el-input v-model="addForm.maxExchange" />
        </el-form-item>
        <el-form-item label="图片" prop="imgUrl">
          <el-upload v-if="!addForm.imgUrl" name="multipartFile" :limit="1" :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload" list-type="picture-card" :action="action" :data="upData"
            :headers="headers" :on-error="fileUploadError" class="imgUpload"><i size="12"
              class="el-icon-plus" /><br /><span class="txt">上传</span></el-upload>
          <!-- <img v-if="addForm.imgUrl" :src="addForm.imgUrl" style="width: 70px;height: 70px;" alt=""> -->
          <template v-if="addForm.imgUrl">
            <div style="display: flex; width: 150px">
              <img v-if="addForm.imgUrl" :src="addForm.imgUrl" style="width: 70px; height: 70px" alt="" />
              <div style="
                  width: 70px;
                  border-radius: 5px;
                  border: 1px dashed #ccc;
                  text-align: center;
                  color: #ccc;
                  margin-left: 5px;
                ">
                <i style="cursor: pointer" class="el-icon-delete" @click="delImg" />
              </div>
            </div>
          </template>
        </el-form-item>
      </el-form>
    </AddDialog>
  </div>
</template>

<script>
import AddDialog from "@/components/Goods/AddDialog";
import { getToken } from "@/utils/auth";
import {
  getFarmingGoodsList,
  addFarmingGoods,
  updateFarmingGoods,
  delFarmingGoods,
} from "@/api/h5";
export default {
  name: "FarmingGoods",
  components: {
    AddDialog,
  },

  data() {
    return {
      headers: { token: getToken() },
      action: process.env.VUE_APP_UPLOAD_BASE_API + "/file/uploadFile",
      upData: {
        fileType: "0",
      },
      isShowBtn: false,
      width: "50%",
      isSearch: false,
      title: "添加商品",
      showDialog: false,
      name: "",
      addForm: {
        name: "",
        unit: "",
        producerArea: "",
        consumeNum: "",
        maxExchange: "",
        imgUrl: "",
      },
      // tokenName: this.$store.getters.tokenName,
      addRules: {
        name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
          {
            min: 1,
            max: 15,
            message: "长度在1到15个字符",
            trigger: "blur",
          },
          {
            pattern: /^[^\’\<\>\%\&\{\}\￥\@\$\'\"\【\】\\\/\ ]*$/,
            message: "不能输入特殊字符",
            trigger: "blur",
          },
        ],
        producerArea: [
          {
            required: true,
            message: "请输入产地",
            trigger: "blur",
          },
          {
            min: 1,
            max: 15,
            message: "长度在1到15个字符",
            trigger: "blur",
          },
        ],
        unit: [
          {
            required: true,
            message: "请输入商品单位",
            trigger: "blur",
          },
          {
            min: 1,
            max: 10,
            message: "长度在1到10个字符",
            trigger: "blur",
          },
          {
            pattern: /^[^\’\<\>\%\&\{\}\￥\@\$\'\"\【\】\\\/\ ]*$/,
            message: "不能输入特殊字符",
            trigger: "blur",
          },
        ],
        imgUrl: [
          {
            required: true,
            message: "请上传图片",
            trigger: "blur",
          },
        ],
        consumeNum: [
          {
            required: true,
            message: "请输入消耗数量",
            trigger: "blur",
          },
          {
            pattern: /^\+?[1-9]\d*$/,
            message: "只能输入正整数",
            trigger: "blur",
          },
        ],
        maxExchange: [
          {
            required: true,
            message: "请输入最大兑换数量",
            trigger: "blur",
          },
          {
            pattern: /^([1-9]|10)$/,
            message: "只能输入1-10的整数",
            trigger: "blur",
          },
        ],
      },
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      farmingGoodsList: [],
      id: "",
    };
  },
  created() {
    this.getFarmingGoodsLists();
    console.log(this.$store.getters.imgBaseUrl);
  },
  methods: {
    async getFarmingGoodsLists() {
      if (!this.isSearch) {
        this.name = "";
      }
      const res = await getFarmingGoodsList({ ...this.page, name: this.name });
      if (res.code === 200) {
        const result = res.data;
        this.farmingGoodsList = result.list;
        this.page.pageSize = result.pageSize;
        this.page.pageNum = result.pageNum;
        this.page.total = result.total;
        const $table = this.$refs.xTable1
        $table.loadData(this.farmingGoodsList);
        console.log("farmingGoodsList", this.farmingGoodsList);
      } else {
        // this.$message.error(res.message);
      }
    },
    async searchFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = true;
      this.getFarmingGoodsLists();
    },
    resetFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = false;
      this.name = "";
      this.getFarmingGoodsLists();
    },
    addFn() {
      this.title = "添加商品";
      this.showDialog = true;
    },
    async del(row) {
      const res = await delFarmingGoods({ id: row.id });
      if (res.code === 200) {
        this.$message.success("删除成功");
        if (this.farmingGoodsList.length === 1 && this.page.pageNum > 1)
          this.page.pageNum--;
        this.getFarmingGoodsLists();
      } else {
        // this.$message.error(res.message);
      }
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;

      this.getFarmingGoodsLists();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      this.page.pageNum = val;

      this.getFarmingGoodsLists();
    },
    handleAvatarSuccess(res, file) {
      this.addForm.imgUrl =
        this.$store.getters.imgBaseUrl +
        res.data.filePath +
        res.data.fileNewName;
      console.log(res);
      console.log(this.addForm.imgUrl, "img");
      this.$message.success("上传成功");
    },
    beforeAvatarUpload(file) {
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf("."));
      const isOKType =
        fileType === ".jpg" || fileType === ".png" || fileType === ".jpeg";
      if (!isOKType) {
        this.$message.error("图片格式只能为jpeg/png/jpg");
      }

      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB!");
      }
      return isLt2M && isOKType;
    },
    fileUploadError(res) {
      this.$message.error(res.message);
    },
    close() {
      this.showDialog = false;
      this.addForm = {
        name: "",
        unit: "",
        producerArea: "",
        consumeNum: "",
        maxExchange: "",
        imgUrl: "",
      };
      this.$refs.addFormRef.resetFields();
    },
    btnOk() {
      // 判断是新增还是修改
      if (this.title === "添加商品") {
        // 新增
        this.$refs.addFormRef.validate(async (isOk) => {
          if (isOk) {
            //
            const res = await addFarmingGoods(this.addForm);
            if (res.code === 200) {
              this.$message.success("新增成功");
              this.getFarmingGoodsLists();
              this.close();
            } else {
              // this.$message.error(res.message);
            }
          } else {
            this.$message.warning("请检查输入信息");
          }
        });
      } else if (this.title === "详情") {
        // 关闭
        this.close();
      } else if (this.title === "修改") {
        // 修改
        this.$refs.addFormRef.validate(async (isOk) => {
          if (isOk) {
            const res = await updateFarmingGoods({
              ...this.addForm,
              id: this.id,
            });
            if (res.code === 200) {
              this.$message.success("修改成功");
              this.getFarmingGoodsLists();
              this.close();
            } else {
              // this.$message.error(res.message);
            }
          } else {
            this.$message.warning("请检查输入信息");
          }
        });
      }
    },
    edit(row) {
      this.showDialog = true;
      this.title = "修改";
      console.log(row);
      this.id = row.id;
      this.addForm.name = row.name;
      this.addForm.unit = row.unit;
      this.addForm.producerArea = row.producerArea;
      this.addForm.consumeNum = row.consumeNum;
      this.addForm.maxExchange = row.maxExchange;
      this.addForm.imgUrl = row.imgUrl;
    },
    delImg() {
      this.addForm.imgUrl = "";
    },
  },
};
</script>

<style scoped lang="scss">
.imgUpload {
  ::v-deep .el-upload:hover {
    border-color: #409eff;
  }

  ::v-deep .el-upload {
    position: relative;
    margin-bottom: 10px;
    margin-left: 5px;
    width: 70px;
    height: 70px;
    line-height: 30px;
    padding-top: 5px;
  }

  .txt {
    color: #595858;
    font-size: 12px;
  }
}

.el-upload--picture-card i {
  font-size: 12px !important;
}
</style>
